# EndoSight-UC AI推理服务器 V3.0 堡垒安全版本
# 多阶段构建 + 非root用户 + 最小攻击面

# Stage 1: Build Stage
FROM python:3.9-slim AS builder

# 设置工作目录
WORKDIR /app

# 安装系统依赖（构建阶段）
RUN apt-get update && apt-get install -y \
    build-essential \
    libmagic1 \
    libmagic-dev \
    && rm -rf /var/lib/apt/lists/*

# 复制requirements文件
COPY requirements.txt .

# 创建虚拟环境并安装依赖
RUN python -m venv /opt/venv \
    && . /opt/venv/bin/activate \
    && pip install --no-cache-dir --upgrade pip setuptools wheel \
    && pip install --no-cache-dir -r requirements.txt \
    && pip install --no-cache-dir gunicorn

# 清理不必要的文件
RUN rm -rf /root/.cache/pip

# Stage 2: Runtime Stage (最小化攻击面)
FROM python:3.9-slim

# 设置安全标签
LABEL maintainer="EndoSight-UC Team"
LABEL version="3.0.0"
LABEL security="hardened"

# 设置工作目录
WORKDIR /app

# 仅安装运行时必需的系统依赖
RUN apt-get update && apt-get install -y \
    libmagic1 \
    libmagic-dev \
    curl \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# [修复 H1] 创建非root用户和组
RUN groupadd -r appuser && useradd -r -g appuser appuser

# 创建必要的目录并设置权限
RUN mkdir -p /app/logs /app/uploads \
    && chown -R appuser:appuser /app \
    && chmod 755 /app

# 复制虚拟环境
COPY --from=builder /opt/venv /opt/venv

# 复制应用代码
COPY --chown=appuser:appuser ./uc_model /app/uc_model
COPY --chown=appuser:appuser ./core /app/core
COPY --chown=appuser:appuser inference_server_v3.py /app/

# 复制配置文件模板
COPY --chown=appuser:appuser .env.example /app/.env.example

# 设置环境变量
ENV PATH="/opt/venv/bin:$PATH"
ENV PYTHONPATH="/app"
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1

# 切换到非root用户
USER appuser

# 创建日志目录
RUN mkdir -p /app/logs && chmod 755 /app/logs

# 验证安装
RUN python -c "import torch; import fastapi; import magic; print('✅ Dependencies verified')"

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -f http://localhost:5001/health || exit 1

# 暴露端口
EXPOSE 5001

# 使用Gunicorn启动（多worker + 安全配置）
CMD ["gunicorn", \
     "--bind", "0.0.0.0:5001", \
     "--workers", "4", \
     "--worker-class", "uvicorn.workers.UvicornWorker", \
     "--worker-connections", "1000", \
     "--max-requests", "1000", \
     "--max-requests-jitter", "100", \
     "--timeout", "30", \
     "--keep-alive", "2", \
     "--access-logfile", "/app/logs/access.log", \
     "--error-logfile", "/app/logs/error.log", \
     "--log-level", "info", \
     "--capture-output", \
     "inference_server_v3:app"]